<template>
  <div class="app-container">
    <header class="header">
      <h1>装修家电统计表格</h1>
      <p class="subtitle">导出时间：{{ currentTime }}</p>
    </header>

    <div class="controls">
      <div class="control-group">
        <button @click="addRow" class="btn btn-primary">
          <span class="icon">+</span> 添加行
        </button>
        <button @click="clearData" class="btn btn-warning">
          <span class="icon">🗑️</span> 清空数据
        </button>
      </div>
      
      <div class="control-group">
        <button @click="exportExcel" class="btn btn-success">
          <span class="icon">📊</span> 导出Excel
        </button>
        <button @click="exportJson" class="btn btn-info">
          <span class="icon">💾</span> 导出JSON
        </button>
        <input 
          type="file" 
          ref="fileInput" 
          @change="importJson" 
          accept=".json" 
          style="display: none"
        >
        <button @click="$refs.fileInput.click()" class="btn btn-secondary">
          <span class="icon">📁</span> 导入JSON
        </button>
      </div>
    </div>

    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>序号</th>
            <th>产品名称</th>
            <th>品牌/型号</th>
            <th>数量</th>
            <th>预算价格(元)</th>
            <th>实际价格(元)</th>
            <th>购买途径</th>
            <th>状态</th>
            <th>备注</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in appliances" :key="item.id">
            <td>{{ index + 1 }}</td>
            <td>
              <input 
                v-model="item.name" 
                type="text" 
                placeholder="例如: 冰箱"
                class="input-field"
              >
            </td>
            <td>
              <input 
                v-model="item.brand" 
                type="text" 
                placeholder="例如: 海尔 BCD-575WDVP"
                class="input-field"
              >
            </td>
            <td>
              <input 
                v-model.number="item.quantity" 
                type="number" 
                min="1" 
                class="input-field input-number"
              >
            </td>
            <td>
              <input 
                v-model.number="item.budgetPrice" 
                type="number" 
                min="0" 
                step="0.01"
                placeholder="0.00"
                class="input-field input-number"
              >
            </td>
            <td>
              <input 
                v-model.number="item.actualPrice" 
                type="number" 
                min="0" 
                step="0.01"
                placeholder="0.00"
                class="input-field input-number"
              >
            </td>
            <td>
              <select v-model="item.purchaseChannel" class="select-field">
                <option value="">--请选择--</option>
                <option value="京东">京东</option>
                <option value="天猫">天猫</option>
                <option value="淘宝">淘宝</option>
                <option value="苏宁易购">苏宁易购</option>
                <option value="国美">国美</option>
                <option value="品牌官网">品牌官网</option>
                <option value="线下实体店">线下实体店</option>
                <option value="其他">其他</option>
              </select>
            </td>
            <td>
              <select v-model="item.status" class="select-field status-select">
                <option value="">--请选择--</option>
                <option value="待购">待购</option>
                <option value="已比价">已比价</option>
                <option value="已下单">已下单</option>
                <option value="已付款">已付款</option>
                <option value="已收货">已收货</option>
                <option value="已安装">已安装</option>
              </select>
            </td>
            <td>
              <input 
                v-model="item.notes" 
                type="text" 
                placeholder="备注信息"
                class="input-field"
              >
            </td>
            <td>
              <button @click="removeRow(index)" class="btn btn-danger btn-small">
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="statistics">
      <div class="stat-card">
        <h3>预算统计</h3>
        <div class="stat-item">
          <span class="label">总预算:</span>
          <span class="value budget">{{ totalBudget.toFixed(2) }} 元</span>
        </div>
        <div class="stat-item">
          <span class="label">实际支出:</span>
          <span class="value actual">{{ totalActual.toFixed(2) }} 元</span>
        </div>
        <div class="stat-item">
          <span class="label">预算差额:</span>
          <span class="value" :class="budgetDifference >= 0 ? 'positive' : 'negative'">
            {{ budgetDifference.toFixed(2) }} 元
          </span>
        </div>
      </div>
      
      <div class="stat-card">
        <h3>商品统计</h3>
        <div class="stat-item">
          <span class="label">商品总数:</span>
          <span class="value">{{ totalQuantity }} 件</span>
        </div>
        <div class="stat-item">
          <span class="label">已完成:</span>
          <span class="value completed">{{ completedCount }} / {{ appliances.length }}</span>
        </div>
        <div class="stat-item">
          <span class="label">完成进度:</span>
          <span class="value progress">{{ completionRate }}%</span>
        </div>
      </div>
    </div>


  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import ExcelJS from 'exceljs'
import { saveAs } from 'file-saver'

export default {
  name: 'App',
  setup() {
    const appliances = ref([])
    const currentTime = ref('')
    
    // 初始化数据
    const initializeData = () => {
      const savedData = localStorage.getItem('applianceData')
      if (savedData) {
        try {
          appliances.value = JSON.parse(savedData)
        } catch (error) {
          console.error('解析本地数据失败:', error)
          appliances.value = [createNewItem()]
        }
      } else {
        appliances.value = [createNewItem()]
      }
    }
    
    // 创建新项目
    const createNewItem = () => ({
      id: Date.now() + Math.random(),
      name: '',
      brand: '',
      quantity: 1,
      budgetPrice: 0,
      actualPrice: 0,
      purchaseChannel: '',
      status: '',
      notes: ''
    })
    
    // 更新当前时间
    const updateCurrentTime = () => {
      const now = new Date()
      currentTime.value = now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
    
    // 添加行
    const addRow = () => {
      appliances.value.push(createNewItem())
    }
    
    // 删除行
    const removeRow = (index) => {
      if (appliances.value.length > 1) {
        appliances.value.splice(index, 1)
      }
    }
    
    // 清空数据
    const clearData = () => {
      if (confirm('确定要清空所有数据吗？此操作不可恢复！')) {
        appliances.value = [createNewItem()]
        localStorage.removeItem('applianceData')
      }
    }
    
    // 计算属性
    const totalBudget = computed(() => {
      return appliances.value.reduce((sum, item) => {
        return sum + (item.budgetPrice || 0) * (item.quantity || 1)
      }, 0)
    })
    
    const totalActual = computed(() => {
      return appliances.value.reduce((sum, item) => {
        return sum + (item.actualPrice || 0) * (item.quantity || 1)
      }, 0)
    })
    
    const budgetDifference = computed(() => {
      return totalBudget.value - totalActual.value
    })
    
    const totalQuantity = computed(() => {
      return appliances.value.reduce((sum, item) => {
        return sum + (item.quantity || 1)
      }, 0)
    })
    
    const completedCount = computed(() => {
      return appliances.value.filter(item => item.status === '已安装').length
    })
    
    const completionRate = computed(() => {
      if (appliances.value.length === 0) return 0
      return Math.round((completedCount.value / appliances.value.length) * 100)
    })
    
    // 导出Excel（使用ExcelJS实现高级样式）
    const exportExcel = async () => {
      const workbook = new ExcelJS.Workbook()
      const worksheet = workbook.addWorksheet('装修家电统计表格')
      
      // 设置列宽
      worksheet.columns = [
        { width: 8 },   // 序号
        { width: 20 },  // 产品名称
        { width: 25 },  // 品牌/型号
        { width: 8 },   // 数量
        { width: 15 },  // 预算价格
        { width: 15 },  // 实际价格
        { width: 15 },  // 购买途径
        { width: 12 },  // 状态
        { width: 20 }   // 备注
      ]
      
      // 添加标题
      worksheet.mergeCells('A1:I1')
      const titleCell = worksheet.getCell('A1')
      titleCell.value = '装修家电统计表格'
      titleCell.font = { name: '微软雅黑', size: 18, bold: true, color: { argb: 'FFFFFF' } }
      titleCell.alignment = { horizontal: 'center', vertical: 'middle' }
      titleCell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: '4472C4' } }
      worksheet.getRow(1).height = 30
      
      // 添加时间信息
      worksheet.mergeCells('A2:I2')
      const timeCell = worksheet.getCell('A2')
      timeCell.value = `导出时间：${currentTime.value}`
      timeCell.font = { name: '微软雅黑', size: 12, color: { argb: '666666' } }
      timeCell.alignment = { horizontal: 'center', vertical: 'middle' }
      timeCell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'F2F2F2' } }
      worksheet.getRow(2).height = 25
      
      // 添加表头
      const headers = ['序号', '产品名称', '品牌/型号', '数量', '预算价格(元)', '实际价格(元)', '购买途径', '状态', '备注']
      worksheet.addRow(headers)
      const headerRow = worksheet.getRow(3)
      headerRow.font = { name: '微软雅黑', size: 12, bold: true, color: { argb: 'FFFFFF' } }
      headerRow.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: '70AD47' } }
      headerRow.alignment = { horizontal: 'center', vertical: 'middle' }
      headerRow.height = 25
      
      // 添加数据行
      appliances.value.forEach((item, index) => {
        const row = worksheet.addRow([
          index + 1,
          item.name || '',
          item.brand || '',
          item.quantity || 1,
          item.budgetPrice || 0,
          item.actualPrice || 0,
          item.purchaseChannel || '',
          item.status || '',
          item.notes || ''
        ])
        
        // 设置行样式
        row.height = 22
        row.font = { name: '微软雅黑', size: 11 }
        row.alignment = { vertical: 'middle' }
        
        // 交替行颜色
        if (index % 2 === 1) {
          row.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'F8F9FA' } }
        }
        
        // 状态列着色
        const statusCell = row.getCell(8)
        switch (item.status) {
          case '已安装':
            statusCell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'C6EFCE' } }
            statusCell.font = { name: '微软雅黑', size: 11, color: { argb: '006100' } }
            break
          case '已收货':
            statusCell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFEB9C' } }
            statusCell.font = { name: '微软雅黑', size: 11, color: { argb: '9C5700' } }
            break
          case '待购':
            statusCell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFC7CE' } }
            statusCell.font = { name: '微软雅黑', size: 11, color: { argb: '9C0006' } }
            break
        }
        
        // 价格列格式化
        row.getCell(5).numFmt = '¥#,##0.00'
        row.getCell(6).numFmt = '¥#,##0.00'
        
        // 居中对齐
        row.getCell(1).alignment = { horizontal: 'center', vertical: 'middle' }
        row.getCell(4).alignment = { horizontal: 'center', vertical: 'middle' }
        row.getCell(5).alignment = { horizontal: 'right', vertical: 'middle' }
        row.getCell(6).alignment = { horizontal: 'right', vertical: 'middle' }
        row.getCell(7).alignment = { horizontal: 'center', vertical: 'middle' }
        row.getCell(8).alignment = { horizontal: 'center', vertical: 'middle' }
      })
      
      // 添加统计信息
      const statsStartRow = appliances.value.length + 5
      
      // 统计标题
      worksheet.mergeCells(`A${statsStartRow}:I${statsStartRow}`)
      const statsTitle = worksheet.getCell(`A${statsStartRow}`)
      statsTitle.value = '统计信息'
      statsTitle.font = { name: '微软雅黑', size: 14, bold: true, color: { argb: 'FFFFFF' } }
      statsTitle.alignment = { horizontal: 'center', vertical: 'middle' }
      statsTitle.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'E67E22' } }
      worksheet.getRow(statsStartRow).height = 25
      
      // 统计数据
      const statsData = [
        ['总预算', `¥${totalBudget.value.toFixed(2)}`],
        ['实际支出', `¥${totalActual.value.toFixed(2)}`],
        ['预算差额', `¥${budgetDifference.value.toFixed(2)}`],
        ['商品总数', `${totalQuantity.value} 件`],
        ['已完成', `${completedCount.value} / ${appliances.value.length}`],
        ['完成进度', `${completionRate.value}%`]
      ]
      
      statsData.forEach((stat, index) => {
        const row = worksheet.addRow(['', stat[0], stat[1]])
        row.font = { name: '微软雅黑', size: 11 }
        row.getCell(2).font = { name: '微软雅黑', size: 11, bold: true }
        row.getCell(3).font = { name: '微软雅黑', size: 11, bold: true, color: { argb: '2E75B6' } }
        row.alignment = { vertical: 'middle' }
        row.height = 20
        
        if (index % 2 === 1) {
          row.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'F8F9FA' } }
        }
      })
      
      // 设置边框
      const totalRows = worksheet.rowCount
      for (let row = 1; row <= totalRows; row++) {
        for (let col = 1; col <= 9; col++) {
          const cell = worksheet.getCell(row, col)
          cell.border = {
            top: { style: 'thin', color: { argb: '000000' } },
            left: { style: 'thin', color: { argb: '000000' } },
            bottom: { style: 'thin', color: { argb: '000000' } },
            right: { style: 'thin', color: { argb: '000000' } }
          }
        }
      }
      
      // 导出文件
      const buffer = await workbook.xlsx.writeBuffer()
      const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      saveAs(blob, `装修家电统计表格_${new Date().toISOString().slice(0, 10)}.xlsx`)
    }
    
    // 导出JSON
    const exportJson = () => {
      const dataToExport = {
        exportTime: currentTime.value,
        appliances: appliances.value,
        statistics: {
          totalBudget: totalBudget.value,
          totalActual: totalActual.value,
          budgetDifference: budgetDifference.value,
          totalQuantity: totalQuantity.value,
          completedCount: completedCount.value,
          completionRate: completionRate.value
        }
      }
      
      const jsonStr = JSON.stringify(dataToExport, null, 2)
      const blob = new Blob([jsonStr], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `装修家电数据_${new Date().toISOString().slice(0, 10)}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }
    
    // 导入JSON
    const importJson = (event) => {
      const file = event.target.files[0]
      if (!file) return
      
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const data = JSON.parse(e.target.result)
          
          // 验证数据格式
          if (!data.appliances || !Array.isArray(data.appliances)) {
            throw new Error('无效的数据格式')
          }
          
          // 验证每个项目的数据结构
          const validData = data.appliances.map(item => ({
            id: item.id || Date.now() + Math.random(),
            name: item.name || '',
            brand: item.brand || '',
            quantity: Number(item.quantity) || 1,
            budgetPrice: Number(item.budgetPrice) || 0,
            actualPrice: Number(item.actualPrice) || 0,
            purchaseChannel: item.purchaseChannel || '',
            status: item.status || '',
            notes: item.notes || ''
          }))
          
          if (confirm(`确定要导入 ${validData.length} 条数据吗？这将覆盖当前所有数据！`)) {
            appliances.value = validData
            alert('数据导入成功！')
          }
        } catch (error) {
          alert('导入失败：' + error.message)
        }
      }
      reader.readAsText(file)
      
      // 清空文件输入
      event.target.value = ''
    }
    
    // 监听数据变化，自动保存到本地存储
    watch(appliances, (newValue) => {
      localStorage.setItem('applianceData', JSON.stringify(newValue))
    }, { deep: true })
    

    
    // 组件挂载时初始化
    onMounted(() => {
      initializeData()
      updateCurrentTime()
      
      // 每秒更新时间
      setInterval(updateCurrentTime, 1000)
      

    })
    
    return {
      appliances,
      currentTime,
      addRow,
      removeRow,
      clearData,
      exportExcel,
      exportJson,
      importJson,
      totalBudget,
      totalActual,
      budgetDifference,
      totalQuantity,
      completedCount,
      completionRate,

    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 30px;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.header h1 {
  font-size: 2.5rem;
  margin-bottom: 10px;
  font-weight: 700;
}

.subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
}

.controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  flex-wrap: wrap;
  gap: 15px;
}

.control-group {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.btn {
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-success {
  background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
  color: white;
}

.btn-warning {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.btn-info {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.btn-secondary {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  color: #333;
}

.btn-danger {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
  color: white;
}

.btn-small {
  padding: 8px 15px;
  font-size: 12px;
}

.icon {
  font-size: 16px;
}

.table-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 30px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px 12px;
  text-align: center;
  font-weight: 600;
  font-size: 14px;
}

.data-table td {
  padding: 12px;
  border-bottom: 1px solid #e9ecef;
  vertical-align: middle;
}

.data-table tbody tr:hover {
  background-color: #f8f9fa;
}

.input-field, .select-field {
  width: 100%;
  padding: 8px 12px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.input-field:focus, .select-field:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.input-number {
  text-align: right;
}

.status-select {
  font-weight: 600;
}

.statistics {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 30px;
}

.stat-card {
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  border-left: 5px solid #667eea;
}

.stat-card h3 {
  color: #2c3e50;
  margin-bottom: 20px;
  font-size: 1.3rem;
  font-weight: 700;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #f1f3f4;
}

.stat-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.label {
  font-weight: 600;
  color: #5a6c7d;
}

.value {
  font-weight: 700;
  font-size: 1.1rem;
}

.budget {
  color: #3498db;
}

.actual {
  color: #e74c3c;
}

.positive {
  color: #27ae60;
}

.negative {
  color: #e74c3c;
}

.completed {
  color: #27ae60;
}

.progress {
  color: #f39c12;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 15px;
  }
  
  .header h1 {
    font-size: 2rem;
  }
  
  .controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .control-group {
    justify-content: center;
  }
  
  .table-container {
    overflow-x: auto;
  }
  
  .data-table {
    min-width: 800px;
  }
  
  .statistics {
    grid-template-columns: 1fr;
  }
  

}
</style>